using System;
using Unity.Mathematics;
using UnityEngine;

namespace GpuHud
{
    [Serializable]
    public class GpuHudImageStyleAsset : GpuHudStyleBase<ImageStyleShaderData>
    {
        //须传入MainTex一致的Sprite，一种Asset对应一种DataCollection代表同一批次
        //如需不同Tex下的Sprite
        //1.支持TextureArray（支持动态加载与卸载，两倍内存）
        //2.使用多个DataCollection（每个Collection中数量较少时）
        [SerializeField]
        private Sprite[] m_Sprites;
        
        [SerializeField]
        public bool preserveAspect;
        
        public Sprite sprite => m_Sprites[m_StateIdx];

        public override int StateCount
        {
            get => base.StateCount;
            set
            {
                base.StateCount = value;
                Array.Resize(ref m_Sprites, value);
            }
        }

        public override void RemoveStateAt(int idx)
        {
            base.RemoveStateAt(idx);
            RemoveAt(ref m_Sprites, idx);
        }
        
        //使用全局缓存UVRect
        //private Dictionary<string, float4> m_SpriteRects = new Dictionary<string, float4>();
        
        
        /// <summary>
        /// rect.x/texW, rect.y/texH, rect.width/texW, rect.height/texH
        /// </summary>
        private float4 UVRect
        {
            get
            {
                if (sprite == null)
                    return default;
                m_ShaderOriginData[m_StateIdx].UVRect = GpuHudUtils.GetUVRect(sprite);
                return m_ShaderOriginData[m_StateIdx].UVRect;
            }
        }

        public override ImageStyleShaderData ShaderOriginData
        {
            get
            {
                m_ShaderOriginData[m_StateIdx].UVRect = UVRect;
                return m_ShaderOriginData[m_StateIdx];
            }
        }

        //统一刷新接口
        public override void RebuildShaderData(GpuHudStyleDataAccessor<ImageStyleShaderData> accessor)
        {
            base.RebuildShaderData(accessor);
/*            var styleAccessor = (GpuHudImageStyleAccessor)accessor; 
            styleAccessor.ShaderCacheData[0].Position = ShaderOriginData.Position + (float3)styleAccessor.m_dataAccessor.Position;
            styleAccessor.ShaderCacheData[0].Size = ShaderOriginData.Size;
            styleAccessor.ShaderCacheData[0].UVRect = GpuHudUtils.GetUVRect(styleAccessor.sprite);
            
            //临时手动刷新, 全局刷新未开启
            styleAccessor.SetShaderData(styleAccessor.ShaderCacheData[0]);//Set Self Cache Data*/
        }
    }

}